package com.whosly.strategy.extractor;

import com.google.common.collect.Sets;
import com.whosly.strategy.container.IStrategyContainer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Set;

/**
 * @Author yueny09 <deep_blue_yang@126.com>
 * @Date 2019-09-06 09:28
 */
public class StrategyContainerExtractor {
    /**
     * 根据 clazz 得到 该 clazz 的接口上的IStrategyContainer接口的 Type 描述
     * @param clazz
     * @return
     */
    public static Type getInterfaceType(Class<?> clazz){
        Set<Type> typeInterfaceList = Sets.newHashSet();

        for (Class<?> current = clazz; current != null; current = current.getSuperclass()) {
            if (current == Object.class) {
                break;
            }

            typeInterfaceList.addAll(Arrays.asList(current.getGenericInterfaces()));
            for (Class<?> now : current.getInterfaces()) {
                Type[] types = now.getGenericInterfaces();
                typeInterfaceList.addAll(Arrays.asList(types));
            }
        }


        if(typeInterfaceList.isEmpty()){
            return null;
        }

        for (Type type : typeInterfaceList){
            if (type instanceof ParameterizedType) { // 处理泛型类型
                String autlalName = ((ParameterizedType)type).getRawType().getTypeName();
                if(autlalName.equals(IStrategyContainer.class.getName())){
                    return type;
                }
            }else{
                if(type.getTypeName().equals(IStrategyContainer.class.getName())){
                    return type;
                }
            }
        }

        return null;
    }
}
